package cn.ekuma.epos.catalog;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.FlowLayout;

import javax.swing.AbstractListModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.ImageIcon;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.JLabel;
import us.k5n.ui.AccordionPane;
import cn.ekuma.data.dao.bean.IKeyed;
import cn.ekuma.epos.bean.util.ProductInfoHelper;
import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.swing.dialog.JEditorNumberDialog;

import com.openbravo.bean.Product;
import com.openbravo.bean.ProductCategory;
import com.openbravo.bean.Tax;
import com.openbravo.bean.sales.ShoppingCart;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.ImageUtils;
import com.openbravo.editor.JEditorDoublePositive;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.bean.ProductCategoryExt;
import com.openbravo.pos.bean.ProductExt;
import com.openbravo.pos.catalog.JCatalogTab;
import com.openbravo.pos.panels.event.ProductCategoryChangedListener;
import com.openbravo.pos.panels.event.ProductChangedListener;
import com.openbravo.pos.panels.navigator.JProductCategoryNavigator;
import com.openbravo.pos.util.ThumbNailBuilder;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.JCheckBox;

public class JCatalog extends JPanel implements ProductCategoryChangedListener, ProductChangedListener {
	private JTextField textField;
	private JPanel leftpanel;

	//private JXTaskPaneContainer taskPane; 
	AccordionPane taskPane;
	private I_DataLogicSales dlSales;
	private JList m_jListCategories;
	private JPanel rightPanel;
	private JCatalogTab recommendPanel;
	
	private JProductListPanel listPanel;
	private JProductListViewPanel listViewPanel;
	
	CatelogManager manager;
	private JPanel mainPanel;
	private JPanel ManufacturingPanel;
	private JProductCategoryNavigator cateNavgator;
	private JButton btnNewButton_8;
	private JCheckBox allProducts;
	
	private JEditorNumberDialog editorNumberDialog;
	private JLabel cartState;
	private ThumbNailBuilder tnbcat;
	private ThumbNailBuilder tnbbutton;

	public JCatalog(I_DataLogicSales dlSales2, boolean pricevisible, boolean taxesincluded,
			int picWidth, int picHeight) {
		this.dlSales=dlSales2;
		initComponents();
		manager=new CatelogManager(dlSales,pricevisible,taxesincluded,picWidth,picHeight);
		tnbcat = new ThumbNailBuilder(32, 32, "com/openbravo/images/folder_yellow.png");
		tnbbutton = new ThumbNailBuilder(picWidth, picHeight, "com/openbravo/images/package.png");
		
		taskPane=new AccordionPane();
        
        JScrollPane m_jscrollcat = new javax.swing.JScrollPane();
        m_jscrollcat.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        m_jscrollcat.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        m_jListCategories=new JList();
        m_jListCategories.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        m_jListCategories.setFocusable(false);
        m_jListCategories.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                m_jListCategoriesValueChanged(evt);
            }
        });
        m_jscrollcat.setViewportView(m_jListCategories);
        taskPane.addPanel(AppLocal.getIntString("label.categoryPanel.ishot"),m_jscrollcat);
        
        m_jListCategories.setCellRenderer(new SmallCategoryRenderer());
        
        
        cateNavgator=new JProductCategoryNavigator(dlSales);
        cateNavgator.addProductCategoryChangedListener(this);
        taskPane.addPanel(AppLocal.getIntString("label.prodcategory"),cateNavgator);
        
        taskPane.addPanel(AppLocal.getIntString("label.extendlink"),getLinkPanel());
        
        leftpanel.add(taskPane, BorderLayout.CENTER);
        
        recommendPanel=new JCatalogTab();
        rightPanel.add(recommendPanel,BorderLayout.CENTER);
        recommendPanel.setVisible(false);
        recommendPanel.setPreferredSize(new Dimension(100, 100));
        
        
        listPanel=new JProductListPanel(manager);
        listPanel.addProductChangedListener(this);
        mainPanel.add(listPanel,"list");
        
        listPanel.setProductChangedListener(new ProductChangedListener(){
			@Override
			public void baseBeanChanged(IKeyed<String> productID, Product o) {
				reflushRecommendPanel(productID.getKey());
			}
        });
        
        listViewPanel=new JProductListViewPanel(manager);
        mainPanel.add(listViewPanel,"listView");
        listViewPanel.addProductChangedListener(this);
        
	}

	public void loadCatalog() throws BasicException{
		cateNavgator.loadData();
		java.util.List<ProductCategoryExt> categories=manager.getHotCategories();
	    m_jListCategories.setModel(new CategoriesListModel(categories)); // aCatList
	}
	
	private void initComponents() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel toolbar = new JPanel();
		add(toolbar, BorderLayout.NORTH);
		toolbar.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new TitledBorder(null,AppLocal.getIntString("label.shoppingcat"), TitledBorder.LEADING, TitledBorder.TOP, null, null));
		toolbar.add(panel_3, BorderLayout.EAST);
		
		cartState = new JLabel(AppLocal.getIntString("label.shoppingcatdirty"),0);
		panel_3.add(cartState);
		
	    btnNewButton_8 = new JButton(AppLocal.getIntString("Label.Payment"));
		panel_3.add(btnNewButton_8);
		
		JButton btnNewButton_9 = new JButton(AppLocal.getIntString("buttom.removeAll"));
		btnNewButton_9.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				reset();
			}
		});
		panel_3.add(btnNewButton_9);
		
		JPanel panel_4 = new JPanel();
		toolbar.add(panel_4, BorderLayout.CENTER);
		panel_4.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		
		JPanel panel = new JPanel();
		panel_4.add(panel);
		
		JToggleButton btnNewButton = new JToggleButton("显示推荐");
		btnNewButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				recommendPanel.setVisible(!recommendPanel.isVisible());
			}
		});
		panel.add(btnNewButton);
		
		JButton button = new JButton("列表");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showView("list");
			}
		});
		panel.add(button);
		
		JButton btnNewButton_1 = new JButton("列表视图");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showView("listView");
			}
		});
		panel.add(btnNewButton_1);
		
		JButton btnNewButton_3 = new JButton("像册");
		panel.add(btnNewButton_3);
		
		JPanel panel_1 = new JPanel();
		panel_4.add(panel_1);
		
		JButton btnNewButton_2 = new JButton("");
		btnNewButton_2.setIcon(new ImageIcon(JCatalog.class.getResource("/com/openbravo/images/2leftarrow.png")));
		panel_1.add(btnNewButton_2);
		
		JButton btnNewButton_4 = new JButton("");
		btnNewButton_4.setIcon(new ImageIcon(JCatalog.class.getResource("/com/openbravo/images/1leftarrow.png")));
		panel_1.add(btnNewButton_4);
		
		JButton btnNewButton_5 = new JButton("");
		btnNewButton_5.setIcon(new ImageIcon(JCatalog.class.getResource("/com/openbravo/images/1rightarrow.png")));
		panel_1.add(btnNewButton_5);
		
		JButton btnNewButton_6 = new JButton("");
		btnNewButton_6.setIcon(new ImageIcon(JCatalog.class.getResource("/com/openbravo/images/2rightarrow.png")));
		panel_1.add(btnNewButton_6);
		
		allProducts = new JCheckBox(AppLocal.getIntString("label.all"));
		panel_4.add(allProducts);
		
		JPanel panel_2 = new JPanel();
		panel_4.add(panel_2);
		
		textField = new JTextField();
		panel_2.add(textField);
		textField.setColumns(20);
		textField.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				searchProduct();
				textField.selectAll();
			}
		});
		
		JButton btnNewButton_7 = new JButton("");
		btnNewButton_7.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				searchProduct();
			}
		});
		btnNewButton_7.setIcon(new ImageIcon(JCatalog.class.getResource("/com/openbravo/images/search.png")));
		panel_2.add(btnNewButton_7);
		
	    leftpanel = new JPanel();
		add(leftpanel, BorderLayout.WEST);
		leftpanel.setLayout(new BorderLayout(0, 0));
		
		JPanel centerPanel = new JPanel();
		add(centerPanel, BorderLayout.CENTER);
		centerPanel.setLayout(new BorderLayout(0, 0));
		
		 ManufacturingPanel = new JPanel();
		centerPanel.add(ManufacturingPanel, BorderLayout.NORTH);
		
		 mainPanel = new JPanel();
		centerPanel.add(mainPanel, BorderLayout.CENTER);
		mainPanel.setLayout(new CardLayout(0, 0));
		
		rightPanel = new JPanel();
		centerPanel.add(rightPanel, BorderLayout.SOUTH);
		rightPanel.setLayout(new BorderLayout(0, 0));
	}


	protected void searchProduct() {
		String sCode = textField.getText();
		if (sCode.isEmpty()) {
			return;
		}
		try{
		manager.searchProduct(sCode);
		   reflushPanel();
	    } catch (BasicException e) {
		 JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
	   }
	}


	protected void showView(String name) {
		CardLayout cl = (CardLayout) (mainPanel.getLayout());
		if(name.equalsIgnoreCase("list")){
			if(!listPanel.isVisible())
			    listPanel.reflush();
		}else{
			if(!listViewPanel.isVisible())
			   listViewPanel.reflush();
		}
		cl.show(mainPanel, name);
	}
	
	
	public void addActionListener(ActionListener l){
		btnNewButton_8.addActionListener(l);
	}

	private void m_jListCategoriesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_m_jListCategoriesValueChanged

        if (!evt.getValueIsAdjusting()) {
            ProductCategoryExt cat = (ProductCategoryExt) m_jListCategories.getSelectedValue();
            if (cat != null) {
                selectCategoryPanel(cat.getID());
            }
        }
    }//GEN-LAST:event_m_jListCategoriesValueChanged
	
	
	private JPanel getLinkPanel(){
		JPanel p=new JPanel();
		
			p.setLayout(new GridLayout(20,1));
			
			JButton btnNewButton = new JButton(AppLocal.getIntString("label.newProduct"));
			btnNewButton.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					try {
						manager.getNewProductExt();
						reflushPanel();
					} catch (BasicException ex) {
						JMessageDialog.showMessage(JCatalog.this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), ex));
					}
				}
			});
			
			p.add(btnNewButton);
			
			JButton btnNewButton_1 = new JButton(AppLocal.getIntString("label.prefPrice"));
			btnNewButton_1.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					try {
						manager.getPrefPriceProductExt();
						reflushPanel();
					} catch (BasicException ex) {
						JMessageDialog.showMessage(JCatalog.this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), ex));
					}
				}
			});
			p.add(btnNewButton_1);
			
			//JButton btnNewButton_2 = new JButton("我的收藏");
			//p.add(btnNewButton_2);
		return p;
	}
	
	
	 private void selectCategoryPanel(String catid) {
		 try {
			manager.queryByCatId(catid,allProducts.isSelected());
			reflushPanel();
		} catch (BasicException e) {
			JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
		}
	 }
	
	private void reflushPanel() {
		if(listPanel.isVisible())
			listPanel.reflush();
		else if(listViewPanel.isVisible())
			listViewPanel.reflush();	
	}

	@Override
	public void valueSelectChanged(ProductCategory obj) {
		selectCategoryPanel(obj.getID());
	}

	public ShoppingCart getShoppingCart(){
		return manager.getCart();
	}
	
	public void reset(){
		manager.getCart().clear();
		printCartState();
	}

	@Override
	public void baseBeanChanged(IKeyed<String> productID, Product o) {
		Product selected=(Product)o;
		Double unit=manager.getCart().getUnit(selected);
		if(unit==null)
			unit=1.0;
		if(editorNumberDialog==null)
		    editorNumberDialog=JEditorNumberDialog.newJDialog(this, new JEditorDoublePositive());
		editorNumberDialog.setDoubleValue(unit);
		editorNumberDialog.setVisible(true);
		unit=editorNumberDialog.getDoubleValue();
		manager.getCart().addShoppingProduct(selected,unit);
		printCartState();
		reflushRecommendPanel(productID.getKey());
	}


	private void reflushRecommendPanel(String productId) {
		if(recommendPanel.isVisible()){
			rightPanel.remove(recommendPanel);
			recommendPanel=new JCatalogTab();     
			rightPanel.add(recommendPanel, BorderLayout.CENTER);
	           // Add products
	       try {
	    	  List<ProductExt> recommedProducts= manager.getRecommendProducts(productId);
	    	  if(recommedProducts!=null)
	    	    for (ProductExt prod :recommedProducts ) {
		    	   recommendPanel.addButton(new ImageIcon(tnbbutton.getThumbNailText(ImageUtils.readImage(prod.getImage()), getProductLabel(prod))), new SelectedAction(prod));
		        }
			} catch (BasicException e) {
				JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
			}
		  rightPanel.validate();
		}
	}

	private void printCartState() {
		cartState.setText(AppLocal.getIntString("label.shoppingcatdirty",manager.getCart().getLines().size()));
	}
	
	
	private class CategoriesListModel extends AbstractListModel {
        private java.util.List m_aCategories;
        public CategoriesListModel(java.util.List aCategories) {
            m_aCategories = aCategories;
        }
        public int getSize() { 
            return m_aCategories.size(); 
        }
        public Object getElementAt(int i) {
            return m_aCategories.get(i);
        }    
    }
    
    private class SmallCategoryRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus);
            ProductCategoryExt cat = (ProductCategoryExt) value;
            setText(cat.getName());
            setIcon(new ImageIcon(tnbcat.getThumbNail(ImageUtils.readImage(cat.getImage()))));
            return this;
        }      
    }
    
    
    private class SelectedAction implements ActionListener {
        private ProductExt prod;
        public SelectedAction(ProductExt prod) {
            this.prod = prod;
        }
        
        public void actionPerformed(ActionEvent e) {
        	baseBeanChanged(prod,prod);
        }
    }
    
    private String getProductLabel(ProductExt product) {
        if (manager.isPricevisible()) {
            if (manager.isTaxesincluded()) {
                Tax tax = manager.getTaxInfo(product.getTaxCategoryID());
                return "<html><center>" + product.getName() + "<br>" + ProductInfoHelper.printPriceSellTax(product, tax);
            } else {
                return "<html><center>" + product.getName() + "<br>" + ProductInfoHelper.printPriceSell(product);
            }
        } else {
            return product.getName();
        }
    }
}
